package com.yzg.simple.nio;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @ClassName ChannelBuffer
 * @Description TODO
 * @Authoe weiyan
 * @Date 2019/12/21 10:12
 * @Version 1.0
 * （读写）渠道对Buffer 进行操作
 *
 * mappedByteBuffer 这个对象是在堆外的操作，相对来说 效率比较高  是用来更改数据的，单位:字节
 **/
public class ChannelBuffer {

    public static void main(String[] args) throws Exception {
        RandomAccessFile randomAccessFile = new RandomAccessFile("d://hello.txt","rw");
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) randomAccessFile.length());
        FileChannel wrChannel = randomAccessFile.getChannel();
      int temp = 0;
            //必须clear 不然读取之后  position = limit  在读取永远都是0 不可能为-1
            byteBuffer.clear();
              temp =  wrChannel.read(byteBuffer);
              byteBuffer.flip();
              // 进行写出修改
              MappedByteBuffer mappedByteBuffer = wrChannel.map(FileChannel.MapMode.READ_WRITE, 0, randomAccessFile.length());
              mappedByteBuffer.put("哈".getBytes());
                  wrChannel.close();
                  randomAccessFile.close();

    }
}